<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>节流与防抖</title>
    <style>
      .box {
        width: 70%;
        height: 10vh;
        background-color: #444444;
        color: #fff;
        line-height: 10vh;
        text-align: center;
        font-size: 18px;
        margin-bottom: 30px;
      }
    </style>
  </head>
  <body>
    <div class="box" id="box1">防抖0</div>
    <div class="box" id="box2">节流0</div>
    <script>
      function debounce(fn, wait) {
        var timer
        return function () {
          var context = this
          var args = arguments
          if (timer) clearTimeout(timer)
          timer = setTimeout(function () {
            fn.apply(context, args);
          }, wait)
        }
      }
      function throttle(fn,wait){
        var timer;
        return function() {
          var context = this;
          var args = arguments;
          if(!timer){
            timer = setTimeout(function() {
              fn.apply(context,args);
              clearTimeout(timer);
              timer = null;
            },wait);
          }
        }
      }
      var debounceCounter = 0;
      var throttleCounter = 0;
      var moveCb = function () {
        var prev = this.innerHTML;
        var prefix = prev.substr(0,2);
        this.innerHTML = prefix + ++debounceCounter;
      }
      var debouncedMoveCb = debounce(moveCb, 200)
      var moveCb2 = function () {
        var prev = this.innerHTML;
        var prefix = prev.substr(0,2);
        this.innerHTML = prefix + ++throttleCounter;
      }
      var throttleCb = throttle(moveCb2,500);
      document
        .querySelector('#box1')
        .addEventListener('mousemove', debouncedMoveCb);
      document.querySelector('#box2').addEventListener('mousemove',throttleCb);
    </script>
  </body>
</html>
